import {useCallback, useEffect, useMemo, useState} from 'react';
import {FlatList, ScrollView, StyleSheet, Text, View} from 'react-native';
import {Empty, GridThree, ObserverText, ObserverView} from '../../components';
import {ArticleList, CategoryList} from '../../services';
import {dpw10, dpw12, dpw20, dpw4, dpw40, dpw8} from '../../constants';
import {useTableReducer} from '../../hooks';

const twoTitle = [
  {
    Name: 'all',
    Id: -1,
    classType: 2,
  },
  {
    Name: 'serialization',
    Id: 1,
    classType: 2,
  },
  {
    Name: 'hasFinish',
    Id: 2,
    classType: 2,
  },
];

const threeTitle = [
  {
    Name: 'all',
    Id: -1,
    classType: 3,
  },
  {
    Name: 'LatestRelease',
    Id: 1,
    classType: 3,
  },
  {
    Name: 'recentUpdates',
    Id: 2,
    classType: 3,
  },
  {
    Name: 'WeeklyPopularity',
    Id: 3,
    classType: 3,
  },
  {
    Name: 'vip',
    Id: 4,
    classType: 3,
  },
];

interface ClassisType {
  /** 类目id */
  Id: number;
  /** 内容类型 漫画-1 小说-2 视频-3 */
  Type?: number;
  /** 类目名字 */
  Name: string;
  classType?: number;
}

const Category = ({route, navigation}: any) => {
  const {typeId, bId} = route.params || {};
  const [classis, setClassis] = useState<ClassisType[]>([]);
  const [actId, setActId] = useState<number | undefined>(); // 分类
  const [acttId, setActtId] = useState(twoTitle[0].Id); // 状态
  const [acttrId, setActtrId] = useState(threeTitle[0].Id); // 关键词
  const [{data, total, loading, pageIndex}, dispatch] = useTableReducer({
    total: 0,
    data: [],
    pageIndex: 1,
    pageSize: 10,
    loading: false,
  });

  useEffect(() => {
    if (bId) {
      setActId(Number(bId));
    } else {
      setActId(-1);
    }
  }, [bId]);

  const getData = useCallback(
    ({cId, statusId, otherId, index, isMore = false}: any) => {
      ArticleList({
        Category: cId,
        Status: statusId,
        Type: otherId,
        PageIndex: index,
        pageSize: 10,
        ArticleType: typeId || 1,
      })
        .then((res: any) => {
          if (!Array.isArray(res?.Data)) {
            dispatch({type: 'error'});
          } else {
            dispatch({
              type: 'success',
              payload: {
                data: isMore
                  ? (preD: any[]) => [...preD, ...res.Data]
                  : res?.Data,
                total: res?.Count,
                pageIndex: index,
              },
            });
          }
        })
        .catch(() => {
          dispatch({type: 'error'});
        });
    },
    [typeId, dispatch],
  );

  // 获取列表数据
  useEffect(() => {
    if (actId) {
      getData({cId: actId, statusId: acttId, otherId: acttrId, index: 1});
    }
  }, [actId, acttId, acttrId]);

  // 加载更多
  const onLoadMore = () => {
    if (!loading && typeof total === 'number' && total > (data || []).length) {
      getData({
        cId: actId,
        statusId: acttId,
        otherId: acttrId,
        index: pageIndex + 1,
        isMore: true,
      });
    }
  };

  // 获取分类类别
  useEffect(() => {
    CategoryList({Type: typeId || 1})
      .then((res: any) => {
        if (Array.isArray(res?.Data)) {
          setClassis(res.Data);
        }
      })
      .catch(() => {});
  }, [typeId]);

  const _randItem = ({item}: {item: ClassisType}) => {
    const getIsAct = () => {
      if (item.classType === 2 && acttId === item.Id) {
        return true;
      }
      if (item.classType === 3 && acttrId === item.Id) {
        return true;
      }
      if (!item.classType && item.Id === actId) {
        return true;
      }
      return false;
    };

    const isAct = getIsAct();

    const changeId = () => {
      if (item.classType === 2) {
        setActtId(item.Id);
      } else if (item.classType === 3) {
        setActtrId(item.Id);
      } else {
        setActId(item.Id);
      }
    };

    return (
      <View style={{alignItems: 'center'}}>
        <Text style={styles.classisItem} onPress={changeId}>
          <ObserverText isActive={isAct} tKey={item.Name} type="tab-title" />
        </Text>
        {item.classType ? null : (
          <View style={{position: 'absolute', right: 0, left: 0, bottom: 2}}>
            <ObserverView
              style={{
                marginHorizontal: 'auto',
                width: dpw20,
                height: dpw4,
                borderRadius: dpw8,
                opacity: isAct ? 1 : 0,
              }}
              themeStyle={{backgroundColor: 'color_1'}}
            />
          </View>
        )}
      </View>
    );
  };

  const _randDataItem = ({item}: any) => {
    return <GridThree list={item.list} type={1} navigation={navigation} />;
  };

  return (
    <ObserverView style={styles.box}>
      <View style={styles.classis}>
        <FlatList
          data={classis}
          horizontal={true}
          keyExtractor={item => `${item.Id}`}
          renderItem={_randItem}
          showsHorizontalScrollIndicator={false}
        />
      </View>
      <ObserverView
        style={{
          height: 1,
          borderRadius: dpw4,
          marginHorizontal: dpw12,
          marginVertical: dpw12,
        }}
        themeStyle={{backgroundColor: 'color_9'}}
      />
      <View style={styles.classis}>
        <FlatList
          data={twoTitle}
          horizontal={true}
          keyExtractor={item => `${item.Id}`}
          renderItem={_randItem}
          showsHorizontalScrollIndicator={false}
        />
      </View>
      <View style={styles.classis}>
        <FlatList
          data={threeTitle}
          horizontal={true}
          keyExtractor={item => `${item.Id}`}
          renderItem={_randItem}
          showsHorizontalScrollIndicator={false}
        />
      </View>
      {Array.isArray(data) && data.length > 0 ? (
        <FlatList
          style={styles.fl}
          data={[{Id: 'banner', list: data}]}
          renderItem={_randDataItem}
          keyExtractor={item => `${item.Id}`}
          onEndReachedThreshold={0.1}
          onEndReached={onLoadMore}
        />
      ) : (
        <Empty />
      )}
    </ObserverView>
  );
};

export default Category;

const styles = StyleSheet.create({
  box: {
    flex: 1,
    paddingVertical: dpw12,
  },
  classis: {
    height: dpw40,
    flexDirection: 'row',
  },
  classisItem: {
    paddingHorizontal: dpw10,
    paddingVertical: dpw8,
  },
  fl: {
    marginHorizontal: 'auto',
    paddingHorizontal: dpw12,
  },
});
